package com.taotao.module.bigdata.consumer.service;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * @desc Netty-webSocket推送数据
 * @author liutao
 * @data 2019.04.19
 */
public class SocketIoService {
    static SocketIOServer server;
    static Map<String, SocketIOClient> clientsMap = new HashMap<>();

    public void startServer() throws InterruptedException {


        //添加客户端连接事件
        server.addConnectListener(client -> {
            String sa = client.getRemoteAddress().toString();
            client.getSessionId().toString();
            String clientIp = sa.substring(1, sa.indexOf(":"));//获取设备ip
            Map params = client.getHandshakeData().getUrlParams();

            //获取客户端连接的uuid参数
            Object object = params.get("uuid");
            String uuid = "";
            if (object != null) {
                uuid = ((List<String>) object).get(0);
                //将uuid和连接客户端对象进行绑定
                clientsMap.put(uuid, client);
            }
        });
        server.start();
    }


    /**
     * 给所有连接客户端推送消息
     *
     * @param eventType 推送的事件类型
     * @param message   推送的内容
     */
    public void sendMessageToAllClient(String eventType, String message) {
        Collection<SocketIOClient> clients = server.getAllClients();
        for (SocketIOClient client : clients) {
            client.sendEvent(eventType, message);
        }
    }

    /**
     * 停止服务
     */
    public void stopServer() {
        if (server != null) {
            server.stop();
            server = null;
        }
    }

    public static SocketIOServer getServer() {
        return server;
    }

}
